<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
export default {
  name: 'Upload',
  props: {
    staffPhoto: {
      type: String,
      default: () => {}
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  watch: {
    staffPhoto: {
      handler(newVal) {
        this.imageUrl = newVal
      },
      immediate: true
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传图片
    upload(e) {
      //   console.log(e)
      var COS = require('cos-js-sdk-v5')
      var cos = new COS({
        SecretId: 'AKIDAAuNZVBaiZAxTigNnwoPjmY3HEyUkjSu',
        SecretKey: 'DAqFOGrBE0VjgOpzsUptfAPN4TcU5PTb'
      })
      cos.putObject(
        {
          Bucket: 'xiaobai-1309205491',
          /* 必须 */
          Region: 'ap-nanjing',
          /* 存储桶所在地域，必须字段 */
          Key: 'e.file.name' /* 必须文件名 */,
          StorageClass: 'STANDARD', // 标准
          Body: e.file,
          // 上传文件对象 onProgress:
          function(progressData) {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          this.imageUrl = 'https://' + data.Location // 记得添加协议
          // Location: 'xiaobai-1309205491.cos.ap-nanjing.myqcloud.com/e.file.name'
          // http://localhost:8081/#/employees/details/18/xiaobai?id=1063705989926227968
          //   传值给父组件 - info.vue
          this.$emit('uploadSuccess', this.imageUrl)
        }
      )
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
